import 'package:ezviz_flutter_plugin/constants.dart';
import 'package:ezviz_flutter_plugin/ezviz_event.dart';
import 'package:ezviz_flutter_plugin/ezviz_flutter_plugin.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'enums.dart';
import 'dart:io';

class EzvizCameraView extends StatefulWidget {
  final double width;
  final double height; // 高度需要限制
  final String accessToken;
  final String deviceSerial;
  final int cameraNo;
  EzvizCameraView({
    @required this.height,
    @required this.accessToken,
    @required this.deviceSerial,
    this.cameraNo,
    this.width,
    Key key,
  }) : super(key: key);
  @override
  _EzvizCameraViewState createState() => _EzvizCameraViewState();
}

class _EzvizCameraViewState extends State<EzvizCameraView> {
  EventChannel eventChannel = EventChannel(EzvizFlutterPlugin.getEventChannelId);
  bool showLoading = true; // 显示loading
  bool showFailButton = false; // 显示重试按钮

  /// 开始播放或继续播放
  void startOrContinue() {
    EzvizFlutterPlugin.startToPlay(
      accessToken:
          'at.du1mmksdbac93lmlc7bdrj08d0j8k6ho-1ou0fgevkf-1kpvzlk-xhie1bdci',
      deviceSerial: 'F03174481',
      // deviceSerial: 'F44342664',
      cameraNo: 1,
    );
  }

  /// 在视图创建后调用
  void _onPlatformViewCreated(int id) {
    startOrContinue();
  }

  @override
  void initState() {
    super.initState();
    // WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    //   startOrContinue();
    // });
    // 接收原生传递数据
    eventChannel.receiveBroadcastStream().listen((event) {
      // 102摄像头播放成功，103摄像头播放失败
      if (!(event is int)) return;

      switch (event) {
        // 播放成功
        case EzvizPluginConstants.MSG_REALPLAY_PLAY_SUCCESS:
          EzvizFlutterPlugin.eventBus.fire(EzvizEvent(EzvizStatus.playSuccess));
          setState(() {
            showLoading = false;
            showFailButton = false;
          });
          break;
        // 播放失败
        case EzvizPluginConstants.MSG_REALPLAY_PLAY_FAIL:
          EzvizFlutterPlugin.eventBus.fire(EzvizEvent(EzvizStatus.playFail));
          setState(() {
            showLoading = false;
            showFailButton = true;
          });
          break;
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    EzvizFlutterPlugin.release();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      child: Stack(
        children: [
          Platform.isAndroid
              ? AndroidView(
                  viewType: EzvizFlutterPlugin.getAndroidViewTypeId,
                  onPlatformViewCreated: _onPlatformViewCreated,
                  creationParamsCodec: StandardMessageCodec(),
                )
              : UiKitView(
                  viewType: EzvizFlutterPlugin.getiOSViewTypeId,
                  onPlatformViewCreated: _onPlatformViewCreated,
                  creationParamsCodec: StandardMessageCodec(),
                ),
          // 加载动画
          if (showLoading) _buildLoadingWidget(),
          // 加载失败重试
          if (showFailButton) _buildRefreshButton(),
        ],
      ),
    );
  }

  /// loading等待
  Widget _buildLoadingWidget() {
    return Center(
      child: SizedBox(
        width: 30,
        height: 30,
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation(Colors.white),
        ),
      ),
    );
  }

  /// 视频加载失败，重试按钮
  Widget _buildRefreshButton() {
    return Container(
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () async {
              setState(() {
                showLoading = true;
                showFailButton = false;
              });
              startOrContinue();
            },
            child: Container(
              height: 28,
              decoration: BoxDecoration(
                color: Color(0xFF35C4C4),
                borderRadius: BorderRadius.all(
                  Radius.circular(14),
                ),
              ),
              padding: EdgeInsets.symmetric(
                horizontal: 12,
              ),
              child: Row(
                children: [
                  Image.asset(
                    'images/video_refresh_icon.png',
                    width: 16,
                    height: 16,
                    package: 'ezviz_plugin',
                  ),
                  SizedBox(width: 4),
                  Text(
                    '刷新重试',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
